<?php


namespace app\shop\controller\admin;


use app\shop\common\consts\Consts;
use app\shop\controller\BaseAdminController;
use app\shop\model\user\AdminRoleModel;
use app\shop\model\user\DepartmentModel;
use app\shop\model\user\FriendModel;
use app\shop\model\user\GroupUserModel;
use app\shop\model\user\UserModel;
use app\shop\service\until\FileService;
use app\shop\service\user\AdminRoleService;
use app\shop\service\user\UserService;
use think\App;

class UserController extends BaseAdminController
{

    public function __construct(App $app)
    {
        $this->model = new UserModel();
        $this->withModel = ['department', 'role'];
        $this->search = $this->setSearch();
        $this->sort = ['role_name' => 'role_id'];
        parent::__construct($app);
    }

    function setSearch()
    {
        $where = [];
        $where[] = ['status', '=', 1];
        $where[] = ['user_id', '<>', 1];
        return [
            'like' => ['realname', 'mobile'],
            '=' => ['role_id'],
            'custom' => $where
        ];
    }


    /**
     * 会员列表
     * @return \think\response\Json
     */
    public function getList()
    {
        try {
            $list = parent::getList()->toArray();
            foreach ($list['data'] as &$v) {
                $v['src'] = $v['avatar'];
                $ossUrl = getDiskUrl();
                if (strpos($v['avatar'], $ossUrl) !== false) {
                    $v['avatar'] = str_replace($ossUrl, '', $v['avatar']);
                }
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 设置登录用户信息
     * @return \think\response\Json
     */
    public function setUserInfo()
    {
        try {
            $nick = $this->request->param('nick', '', 'trim');
            $avatar = $this->request->param('avatar', '', 'trim');
            $pwd = $this->request->param('password', '', 'trim');
            $mobile = $this->request->param('mobile', '', 'trim');

            $userInfo = $this->request->middleware('userInfo');
            $userInfo->avatar = $avatar;
            $userInfo->nick = $nick;
            if ($pwd) {
                $userInfo->password = password_hash($pwd . $userInfo->salt, PASSWORD_DEFAULT);
            }
            if ($userInfo->mobile != $mobile) {
                $exist = UserModel::getByMobile($mobile);
                if ($exist) {
                    throw new \Exception('账号已存在');
                }
                $userInfo->mobile = $mobile;
            }
            $userInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户信息
     * @return \think\response\Json
     */
    public function info()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $fullAvatar = $userInfo['avatar'];
            $ossUrl = getDiskUrl();
            $avatar = str_replace($ossUrl, '', $userInfo['avatar']);
            $data = [
                'user_id' => $userInfo['user_id'],
                'realname' => $userInfo['realname'],
                'mobile' => $userInfo['mobile'],
                'avatar' => $avatar,
                'full_avatar' => $fullAvatar,
            ];
            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 获取用户好友列表
     * @return \think\response\Json
     */
    public function getUserFriendList()
    {
        try {
            $id = $this->request->param('user_id', 0, 'int');
            $list = FriendModel::where('create_user', $id)
                ->where('status', 1)
                ->order('create_time', 'desc')
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $v['create_time'] = date('Y-m-d H:i', strtotime($v['create_time']));
                $v['friend_user_name'] = UserModel::where('user_id', $v['friend_user_id'])->value('realname', '');
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 修改用户状态
     * @return \think\response\Json
     */
    public function setUserStatus()
    {
        try {
            $id = $this->request->param('id', 0, 'int');
            $status = $this->request->param('status', 0, 'int');
            if ($id <= 0) {
                throw new \Exception(lang(1001));
            }
            $userInfo = UserModel::find($id);
            if (!$userInfo) {
                throw new \Exception(lang(1002));
            }
            $userInfo->status = $status ? 1 : 0;
            $userInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 添加修改用户
     * @return \think\response\Json
     */
    public function add()
    {
        try {
            $data = $this->request->param('', '', 'trim');
            if (!isset($data['user_id']) || !$data['user_id']) {
                $data['user_sn'] = random(6, 'letter');
                $data['salt'] = random(4);
                $data['avatar'] = '/avatar/1/66bf0a7cb2371.png';
                $data['password'] = password_hash($data['password'] . $data['salt'], PASSWORD_DEFAULT);
                $info = UserModel::where('mobile', $data['mobile'])->find();
                if ($info) {
                    throw new \Exception('手机号已存在');
                }
                $model = new UserModel();
                $model->save($data);
            } else {
                $model = $this->model->find($data['user_id']);
                if ($data['password'] != '') {
                    $data['password'] = password_hash($data['password'] . $model->salt, PASSWORD_DEFAULT);
                } else {
                    $data['password'] = $model->password;
                }
                $info = UserModel::where('mobile', $data['mobile'])->find();
                if ($info && $info['user_id'] != $data['user_id']) {
                    throw new \Exception('手机号已存在');
                }

                unset($data['last_login_time'], $data['create_time']);
                $model->save($data);
            }
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 设计人员列表
     * @return \think\response\Json
     */
    public function getDesignUserArr()
    {
        try {
            $list = UserModel::whereIn('role_id', [Consts::DESIGN_LEADER_ID, Consts::DESIGN_ID])
                ->where('status', 1)
                ->field('user_id,realname')
                ->select()
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 销售人员列表
     * @return \think\response\Json
     */
    public function getSaleUserArr()
    {
        try {
            $list = UserModel::where('role_id', Consts::SALE_ID)
                ->where('status', 1)
                ->field('user_id,realname')
                ->select()
                ->toArray();
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}